# 封装消息通知的逻辑
import zmail
import time
from abc import ABC,abstractmethod
from dingtalkchatbot.chatbot import DingtalkChatbot
from utils.get_test_result_data import  get_test_result_data
from utils.config_parser import GetConfig

class SendMessage(ABC):

    def __init__(self,env):

        # 判断目前是什么环境，就去获取什么地址
        report_link_dict = {
            "test": "report_link_test",
            "prod": "report_link_prod",
            "sting": "report_link_sting"
        }
        report_link = report_link_dict.get(env, "prod")


        self.get_config = GetConfig()
        self.now = time.strftime("%Y-%m-%d %H:%M:%S")
        self.test_result = get_test_result_data()
        self.report_link = self.get_config.get_message_report_path().get(report_link)
        self.passed = self.test_result.get("passed",0)
        self.failed = self.test_result.get("failed",0)
        self.skipped = self.test_result.get("skipped",0)

        # 获取钉钉消息通知配置
        self.config_dingding = self.get_config.get_message_dingding()

        # 获取邮箱消息通知配置
        self.config_email = self.get_config.get_message_email()


    @abstractmethod
    def send_message(self):
        pass

class SendDingDingMessage(SendMessage):
    """
    发送钉钉消息
    """
    def send_message(self):
        ding = DingtalkChatbot(self.config_dingding.get("webhook"),
                               self.config_dingding.get("secret"))
        ding.send_markdown("宣威接口自动化测试报告",f"""
        **宣威接口自动化测试概述**
- **测试时间**：{self.now}
- **测试结果**：
 - 成功：{self.passed}条
 - 失败：{self.failed}条
 - 跳过：{self.skipped}条
<!---->
- **测试报告链接**：[点击访问]({self.report_link})
    """)

class SendMailMessage(SendMessage):
    """
    发送邮件
    """
    def send_message(self):
        mail = zmail.server(self.config_email.get("username"),
                            self.config_email.get("password"))
        mail.send_mail(recipients= self.config_email.get("recipients"),
                       mail={
                           "subject": "宣威接口自动化执行结果通知",
                           "content_html": f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接口自动化测试报告</title>
    <style>
        body {{
            font-family: 'Segoe UI', system-ui, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 2rem auto;
            padding: 0 20px;
            background-color: #f5f5f5;
        }}

        .report-card {{
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 2rem;
        }}

        h1 {{
            color: #2c3e50;
            border-bottom: 3px solid #3498db;
            padding-bottom: 0.5em;
            margin-bottom: 1.5rem;
            font-size: 2.2rem;
        }}

        .metadata {{
            margin-bottom: 1.5rem;
            color: #7f8c8d;
            font-size: 0.95rem;
        }}

        .result-stats {{
            display: flex;
            gap: 2rem;
            margin: 1.5rem 0;
        }}

        .stat-item {{
            flex: 1;
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
        }}

        .success {{
            background: #e8f5e9;
            color: #2e7d32;
        }}

        .failure {{
            background: #ffebee;
            color: #c62828;
        }}

        .skipped {{
            background: #fff8e1;
            color: #ff8f00;
        }}

        a.report-link {{
            display: inline-block;
            padding: 0.8rem 1.5rem;
            background: #3498db;
            color: white !important;
            text-decoration: none;
            border-radius: 6px;
            transition: background 0.3s ease;
        }}

        a.report-link:hover {{
            background: #2980b9;
        }}
    </style>
</head>
<body>
    <article class="report-card">
        <header>
            <h1>接口自动化测试概述</h1>
            <div class="metadata">
                <strong>测试时间：</strong>2023-11-15 14:30:00
            </div>
        </header>

        <section>
            <h2>测试结果</h2>
            <div class="result-stats">
                <div class="stat-item success">
                    <div style="font-size: 1.8rem; font-weight: bold;">{self.passed}</div>
                    <div>成功</div>
                </div>
                <div class="stat-item failure">
                    <div style="font-size: 1.8rem; font-weight: bold;">{self.failed}</div>
                    <div>失败</div>
                </div>
                 <div class="stat-item skipped">
                    <div style="font-size: 1.8rem; font-weight: bold;">{self.skipped}</div>
                    <div>跳过</div>
                </div>
            </div>
        </section>

        <section style="margin-top: 2rem;">
            <a href="full_report.html" class="report-link">点击访问完整测试报告</a>
        </section>
    </article>
</body>
</html>"""})

def send_message(env):
    """
    消息通知的实际调用方法（实际工作中应该只有一种情况，就不需要遍历了）
    """
    message_obj = [
        SendDingDingMessage(env),
        SendMailMessage(env)
    ]

    for mo in message_obj:
        mo.send_message()



if __name__ == '__main__':
    # ding = SendDingDingMessage()
    # ding.send_message()
    # mail = SendMailMessage()
    # mail.send_message()
    send_message("test")